"""
    Author:
    Date: 2019-01-11

    极光推送管理类
"""

import json
import jpush

from django.conf import settings

from utils.log import Log
from entities import user_mgr
from entities import vchat_api_mgr


def push_message(audience, message, extras=None, apns_production=1, user_count=-1):
    """ 给指定的用户推送消息 """
    app_data = settings.APP_DATA
    for bundle_id, app_info in app_data.items():
        jpush_enable = app_info.get('JPUSH_ENABLE', False)
        if not jpush_enable:
            continue

        app_key = app_info.get('JPUSH_APP_KEY', '')
        if not app_key:
            Log.error(f'Not find JPUSH_APP_KEY for {bundle_id}!')
            continue

        app_master_secret = app_info.get('JPUSH_MASTER_SECRET', '')
        if not app_master_secret:
            Log.error(f'Not find JPUSH_MASTER_SECRET for {bundle_id}!')
            continue

        _push_message(app_key, app_master_secret, audience, message, bundle_id, extras, apns_production)
    return True


def _push_message(app_key, app_master_secret, audience, message, bundle_id, extras, apns_production=1):
    """ 使用指定的参数给指定的用户推送消息 """
    if settings.DEBUG:
        return True

    Log.info(f'Push message to {audience}: msg={message}, bundle_id={bundle_id}, extras={extras}, apns={apns_production} ......')
    _jpush = jpush.JPush(app_key, app_master_secret)
    push = _jpush.create_push()
    _jpush.set_logging("DEBUG")

    push.audience = audience
    if extras is None:
        extras = {}
    ios = jpush.ios(alert=message, badge=0, extras=extras)
    android = jpush.android(alert=message, priority=1, style=1, alert_type=1, big_text='', extras=extras)
    push.notification = jpush.notification(alert=message, android=android, ios=ios)
    push.message = jpush.message(message, extras=extras)
    push.options = {"apns_production": apns_production}

    push.platform = jpush.all_
    try:
        response = push.send()
    except jpush.common.Unauthorized:
        Log.error(f'Push message failed for unauthorized: message-{message}, bundle_id={bundle_id}.')
        return False
    except jpush.common.APIConnectionException:
        Log.error(f'Push message failed for api exception: message={message}, bundle_id={bundle_id}.')
        return False
    except jpush.common.JPushFailure:
        Log.error(f'Push message failed: message-{message}, bundle_id={bundle_id}.')
        return False
    except Exception as e:
        Log.error(f'Push message failed for exception: message={message}, bundle_id={bundle_id}, {e}')
        return False

    Log.info(f'Push message ok: message={message}, bundle_id={bundle_id}.')
    return True


def push_message_to_users(uids, message, extras, apns_production):
    """ 给指定的多个用户推送消息 """
    if len(uids) == 1:
        uid = uids[0]
        Log.info(f'Push message to user: uid={uid}, msg={message}, apns={apns_production}')
        return push_message_to_user(uid, message, extras, apns_production)

    alias = [f'{uid}PUSH' for uid in uids]
    audience = jpush.audience({'alias': alias})
    return push_message(audience, message, extras, apns_production)


def push_message_to_all_users(message, extras, apns_production=True):
    """ 给指定的用户推送消息 """
    audience = jpush.all_
    return push_message(audience, message, extras, apns_production)


def push_message_to_user(uid, message, extras, apns_production):
    """ 给指定的用户推送消息 """
    # user = user_mgr.get_user_detail(uid)
    # if user is None:
    #     Log.error(f"Push message to user-{uid} failed: not find user!")
    #     return
    #
    # bundle_id = user['bundle_id']
    # app_info = settings.APP_DATA.get(bundle_id, None)
    # if app_info is None:
    #     Log.error(f"Push message to user-{uid} failed: not find app info for {bundle_id}")
    #     return
    #
    # app_key = app_info.get('JPUSH_APP_KEY', '')
    # if not app_key:
    #     Log.error(f'Push message to user-{uid} failed: Not find JPUSH_APP_KEY for {bundle_id}!')
    #     return
    #
    # app_master_secret = app_info.get('JPUSH_MASTER_SECRET', '')
    # if not app_master_secret:
    #     Log.error(f'Not find JPUSH_MASTER_SECRET for {bundle_id}!')
    #     return
    #
    # alias = [f'{uid}PUSH']
    # audience = jpush.audience({'alias': alias})
    # Log.info(f"Push message to user-{uid}: {message}, bundle_id={bundle_id}, product={apns_production}")
    # return _push_message(app_key, app_master_secret, audience, message, bundle_id, extras, apns_production)

    Log.info(f'Push message to user: uid={uid}, msg={message}, apns={apns_production}')
    extras = json.dumps(extras)
    vchat_api_mgr.push_notice_message_to_user(uid, message, extras, apns_production)
    return True


if __name__ == '__main__':
    print('ok')
